<template>
<div class="addOrEditRoleBox">
  <breadcrumb :titleArr="titleArr" @back="breadcrumbBack" class="bread-crumb"></breadcrumb>

  <div class="base-info">
    <p class="title">基本信息</p>
    <el-form
      class="m7-form addOrEditRoleForm"
      :rules="roleRule"
      size="mini" :model="addOrEditRoleForm"
      ref="addOrEditRoleForm" label-position="top"
    >
      <div class="clearfix">
        <el-form-item label="角色名称" prop="roleName" class="width-one fl">
          <el-input v-model.trim="addOrEditRoleForm.roleName" placeholder="请输入角色名称" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="使用版本" prop="useEdition" class="width-one fr">
          <m7Select filterable size="mini" :disabled="type !=='add'" v-model="addOrEditRoleForm.useEdition"
                    :defaultProps="{value: 'licenceId', label:'name'}"
                    :options="licenceList" @change="licenceChange" placeholder="请选择">
          </m7Select>
        </el-form-item>
      </div>
      <el-form-item label="角色描述" prop="roleDes">
        <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                size="mini"
                v-model.trim="addOrEditRoleForm.roleDes">
        </el-input>
      </el-form-item>
    </el-form>
  </div>

  <div v-if="loading" class="tree-wrap">
    <p class="title">权限设置</p>
    <roleTree :treeData="addOrEditRoleForm.roleTree" :treeLevelNum="0"></roleTree>
  </div>

  <div class="more-btn">
    <el-button size="mini" @click="cancelFun">取消</el-button>
    <el-button size="mini" type="primary" @click="saveFun">保存</el-button>
  </div>
</div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import roleTree from '@/views/config/role/roleTree.vue'
import breadcrumb from '@/components/breadcrumb/breadcrumb.vue'
import { organizationConfigModule } from '@/store/modules/config/organizationConfig/index'
function roleDataHandle (options, limits, functions, scope) {
  for (let i = 0; i < options.length; i++) {
    if (options[i].checked) {
      limits.push(options[i]._id)
    }
    if (options[i].function) {
      for (let j = 0; j < options[i].function.length; j++) {
        if (options[i].function[j].checked) {
          functions.push(options[i].function[j]._id)
        }
      }
    }
    if (options[i].scope) {
      for (let k = 0; k < options[i].scope.length; k++) {
        if (options[i].scope[k].checked) {
          scope.push(options[i].scope[k]._id)
        }
      }
    }
    if (options[i].children && options[i].children.length > 0) {
      roleDataHandle(options[i].children, limits, functions, scope)
    }
  }
  return { limits, functions, scope }
}
@Component({
  name: 'addOrEditRole',
  components: { roleTree, breadcrumb }
})
export default class AddOrEditRole extends Vue {
  @Prop(Array) private licenceList
  @Prop(String) private type
  @Prop({ default: [] }) private titleArr!: any
  [x: string]: any

  private loading = false

  private roleRule = {
    roleName: [{ required: true, trigger: 'blur', message: '请输入2-8位角色名称' }]
  }

  private addOrEditRoleForm = {
    _id: '',
    roleName: '',
    useEdition: (this as any).licenceList[0].licenceId,
    roleDes: '',
    roleTree: []
  }

  private breadcrumbBack () {
    this.$emit('pageBack')
  }

  private cancelFun () {
    this.$emit('cancelFun')
  }

  private saveFun () {
    const roleName = this.addOrEditRoleForm.roleName
    if (roleName === '') {
      this.$message.error('请输入角色名称')
      return false
    } else {
      if (roleName.length > 8 || roleName.length < 2) {
        this.$message.error('请输入2-8位的角色名称')
        return false
      } else {
        const { limits, functions, scope } = roleDataHandle(this.addOrEditRoleForm.roleTree, [], [], [])
        const sendData: any = {
          name: this.addOrEditRoleForm.roleName,
          version: this.addOrEditRoleForm.useEdition,
          description: this.addOrEditRoleForm.roleDes,
          limits,
          scope,
          functions
        }
        let sendUrl = '/base/action/role/create'
        let successMessage = '保存角色成功'
        if (this.addOrEditRoleForm._id !== '') {
          sendUrl = '/base/action/role/update'
          sendData._id = this.addOrEditRoleForm._id
          successMessage = '更新角色成功'
        }
        const actionData = { url: sendUrl, method: 'POST', data: { ...sendData } }
        organizationConfigModule.organizationCommonAction(actionData).then(res => {
          if (res) {
            this.$message.success(successMessage)
            this.$emit('saveRoleFun', this.addOrEditRoleForm._id === '' ? 'add' : null)
            if (!this.addOrEditRoleForm._id) { // 更新缓存
              this.$addOneCache('roleList', res.data[0], true)
            } else {
              this.$updateCache('roleList', res.data, '_id', true)
            }
          }
        })
      }
    }
  }

  public setRoleData (roleValue) {
    if (roleValue) {
      this.addOrEditRoleForm = {
        _id: roleValue.role._id,
        roleName: roleValue.role.name,
        useEdition: roleValue.role.version,
        roleDes: roleValue.role.description,
        roleTree: roleValue.tree
      }
      this.loading = true
    }
  }

  private licenceChange (val: any) {
    this.loading = false
    this.$nextTick(() => {
      this.licenceList.forEach((item: any) => {
        if (val === item.licenceId) {
          this.addOrEditRoleForm.roleTree = item.limits
        }
      })
      this.loading = true
    })
  }

  private mounted () {
    if (this.type === 'add') {
      this.addOrEditRoleForm.roleTree = this.licenceList[0].limits
      this.loading = true
    }
  }
}
</script>
<style lang="stylus" scoped>
  .roleContent
    border 1px solid $border-main
    // padding 10px 16px 30px
    border-radius 10px
    height calc(100vh - 86px)
    overflow auto
    box-shadow 0px 0px 4px 0px #e0e6f0, 0px 1px 4px 0px #e0e6f0
  .bread-crumb
    // margin 10px 0 20px 0
  .width-one
    width 48%
  .more-btn
    bottom -1px
    right 1px
    width 99%
    padding 24px
    line-height initial
    text-align right
    position absolute
    background #fff
    z-index 20
    border-bottom-right-radius 6px
  .base-info
    margin 24px
  .title
    margin-bottom 15px
    color $fc-gray2
    font-size 14px
    font-weight 600
  .tree-wrap
    margin 24px
    margin-top 40px
    margin-bottom 82px
</style>
